<template>
  <div class="main">

    <img src="/static/images/stbg.jpg" class="background"/>

    <view class="avatarstyle">
      <open-data type="userAvatarUrl"></open-data>
    </view>

    <i-row class="usertext">
      <i-col span="8" offset="5">
        <p class="nametext">
          昵称：
          <open-data type="userNickName"></open-data>
        </p>
      </i-col>
      <i-col span="8" offset="1">
        积分：
        {{userscore}}
      </i-col>
    </i-row>

    <div class="choosecls">
      <!--      <img class="userinfo-avatar" :src="userInfo.avatarUrl"/>-->
      <span>{{sltclass}} - {{motto}}</span>
      <i-button @click="showMulPicker" inline="true" shape="circle" size="small" type="warning">选择年级与学科</i-button>
      <mp-picker ref="mpPicker" :mode="'multiSelector'" :deepLength=deepLength
                 @onConfirm="onConfirmPicker" :pickerValueArray="pickerMulArray">
      </mp-picker>

    </div>

    <div>
      <i-button open-type="getUserInfo" @getuserinfo="goMissionPage"
                type="info" shape="circle">
        开始答题
      </i-button>
      <i-button open-type="getUserInfo" @getuserinfo="rankingpage" type="success" shape="circle">排行榜</i-button>
    </div>

<!--    <i-toast id="toast" />-->
    <!--显示加载中的ui-->
    <mp-loading :showLoading="isShowLoading" loadingText="加载中..." :mask="false"></mp-loading>
    <i-message id="message"/>
  </div>

</template>

<script>
  import mpPicker from 'mpvue-weui/src/picker'
  import httpKit from './http-kit'
  import querystring from 'querystring'

  export default {
    data () {
      return {
        userInfo: {
          openid: '',
          nickName: '',
          avatarUrl: ''
        },
        userscore: undefined, //  积分
        sltclass: '', //  年级
        motto: '', //  科目
        pickerMulArray: [
          [
            {label: '一年级'}, {label: '二年级'}, {label: '三年级'},
            {label: '四年级'}, {label: '五年级'}, {label: '六年级'}
          ],
          [ {label: '语文'}, {label: '数学'}, {label: '英语'} ]
        ]
      }
    },
    components: {
      mpPicker
    },
    methods: {
      showMulPicker () {
        this.$refs.mpPicker.show()
      },
      // 选择年级和科目
      onConfirmPicker (e) {
        const sltclass = this.pickerMulArray[0][e.index[0]].label
        const motto = this.pickerMulArray[1][e.index[1]].label
        try {
          wx.setStorageSync('subject', motto)
          wx.setStorageSync('grade', sltclass)
          this.motto = motto
          this.sltclass = sltclass
        } catch (e) {
          this.$Message({
            content: '操作失败!',
            type: 'error'
          })
        }
      },
      goMissionPage (e) {
        this.userInfo.nickName = e.mp.detail.userInfo.nickName
        this.userInfo.avatarUrl = e.mp.detail.userInfo.avatarUrl
        if (!this.isValidSetting()) {
          return
        }
        this.updateUserInfo()
        wx.showLoading({title: '加载中...', mask: true})
        const url = '../../pages/missions/main'
        wx.navigateTo({url})
      },
      /**
       * 跳转到关卡界面前检查用户环境参数
       * @returns {boolean}
       */
      isValidSetting () {
        if (this.userInfo.nickName === '') {
          return false
        }
        if (!this.userInfo.openid) {
          this.login()
          this.$Message({
            content: '正在更新数据,请稍后重试！',
            type: 'error'
          })
          return false
        } else if (this.userscore === undefined) {
          this.getScore()
          this.$Message({
            content: '正在更新积分,请稍后重试！',
            type: 'error'
          })
          return false
        }
        return true
      },
      /**
       * 检查用户信息是否与本地缓存数据相同，
       * 若不同则发送请求更新服务端用户信息
       * @param userInfo
       */
      updateUserInfo () {
        const _this = this
        wx.getStorage({
          key: 'userInfo',
          success: res => {
            if (_this.userInfo.nickName !== res.data.nickName ||
                _this.userInfo.avatarUrl !== res.data.avatarUrl) {
              wx.setStorage({
                key: 'userInfo',
                data: this.userInfo
              })
              httpKit.updateUserInfo(this.userInfo)
            }
          }
        })
      },
      rankingpage (e) {
        this.userInfo.nickName = e.mp.detail.userInfo.nickName
        this.userInfo.avatarUrl = e.mp.detail.userInfo.avatarUrl
        if (!this.isValidSetting()) {
          return
        }
        this.updateUserInfo()
        wx.showLoading({title: '加载中...', mask: true})
        const param = querystring.stringify({
          score: this.userscore,
          openid: this.userInfo.openid
        })
        wx.navigateTo({url: '../../pages/ranking/main?' + param})
      },

      /**
       * 加载程序时登陆以获取用户openid
       * 然后发送请求获取积分
       */
      login () {
        const _this = this
        wx.login({
          success (res) {
            if (res.code) {
              // 发起网络请求
              httpKit.getOpenID(res.code,
                res => {
                  _this.userInfo.openid = res.data.openid
                  _this.getScore()
                }
              )
            } else {
              console.log('登录失败！' + res.errMsg)
            }
          }
        })
      },
      getScore () {
        const _this = this
        // 发送请求获取积分
        httpKit.loginUser(_this.userInfo.openid,
          res => {
            _this.userscore = res.data.data.integral
          }
        )
      }
    },
    created () {
      const subject = wx.getStorageSync('subject')
      const grade = wx.getStorageSync('grade')
      if (subject) {
        this.motto = subject
      } else {
        this.motto = '数学'
        wx.setStorageSync('subject', '数学')
      }
      if (grade) {
        this.sltclass = grade
      } else {
        this.sltclass = '一年级'
        wx.setStorageSync('grade', '一年级')
      }
      const userInfo = wx.getStorageSync('userInfo')
      if (userInfo) {
        this.userInfo.nickName = userInfo.nickName
        this.userInfo.avatarUrl = userInfo.avatarUrl
      } else {
        wx.setStorageSync('userInfo', this.userInfo)
      }
    },
    onShow () {
      if (!this.userInfo.openid) {
        this.login()
      } else {
        this.getScore()
      }
    },
    onHide () {
      wx.hideLoading()
    },
    onPullDownRefresh () {
      if (!this.userInfo.openid) {
        this.login()
      } else {
        this.getScore()
      }
      wx.stopPullDownRefresh()
    }
  }
</script>

<style scoped>
  .main {
    overflow: hidden;
  }
  .background {
    position: fixed;
    height: 100%;
    width: 100%
  }
  .choosecls {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    padding-top: 50px;
    padding-bottom: 70px;
    font-size: 18px;
  }
  .avatarstyle {
    width: 180rpx;
    height: 180rpx;
    overflow: hidden;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    position: relative;
    margin: 50px auto 30px auto;
  }
  .usertext {
    margin: 0 auto;
    position: relative;
    font-size: 18px;
  }

  .nametext {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .scoretext {
    text-align: left;
  }
</style>

